package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.dto.CreateGroupRequest;
import com.zhentao.pojo.ChatGroup;
import com.zhentao.pojo.ChatGroupMember;
import com.zhentao.service.ChatGroupMemberService;
import com.zhentao.service.ChatGroupService;
import com.zhentao.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 群聊相关接口
 * 前缀：/groups
 */
@RestController
@RequestMapping("/groups")
public class GroupController {

    @Autowired
    private ChatGroupService chatGroupService;
    @Autowired
    private ChatGroupMemberService chatGroupMemberService;

    /**
     * 获取我的群组列表
     * GET /groups/my?userId=xxx&keyword=xxx
     */
    @GetMapping("/my")
    public Result<Object> getMyGroups(@RequestParam Long userId,
                                      @RequestParam(required = false) String keyword) {


        if (userId == null) {
            return Result.fail("请输入用户ID");
        }
        // 查询我加入的群
        List<ChatGroupMember> joins = chatGroupMemberService.list(
                new QueryWrapper<ChatGroupMember>().eq("user_id", userId)
        );

        // 判断没有加入群聊的情况
        if (joins.isEmpty()) {
            Map<String, Object> data = new HashMap<>();
            data.put("list", Collections.emptyList());
            return Result.success(data);
        }
        List<Long> groupIds = joins.stream().map(ChatGroupMember::getGroupId).toList();
        List<ChatGroup> groups = chatGroupService.list(
                new QueryWrapper<ChatGroup>()
                        .in("group_id", groupIds)
                        .like(keyword != null && !keyword.isEmpty(), "group_name", keyword)
        );
        // 适配前端字段
        List<Map<String, Object>> list = new ArrayList<>();
        for (ChatGroup g : groups) {
            Map<String, Object> m = new HashMap<>();
            m.put("id", g.getGroupId());
            m.put("name", g.getGroupName());
            m.put("memberCount", g.getMemberCount());
            m.put("lastMessage", "");
            m.put("lastMessageTime", g.getUpdateTime());
            m.put("isMuted", false);
            list.add(m);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("list", list);
        return Result.success(data);
    }

    /**
     * 退出群组
     * POST /groups/{groupId}/leave { userId }
     */
    @PostMapping("/{groupId}/leave")
    public Result<Object> leaveGroup(@PathVariable Long groupId, @RequestBody(required = false) Map<String, Object> body) {
        if (groupId == null) return Result.fail("群组ID不能为空");
        Long userId = null;
        if (body != null && body.get("userId") != null) {
            userId = Long.valueOf(String.valueOf(body.get("userId")));
        }
        if (userId == null) return Result.fail("用户ID不能为空");

        // 先查询该用户是否在群组中，避免不必要的操作
        boolean exists = chatGroupMemberService.count(
                new QueryWrapper<ChatGroupMember>()
                        .eq("group_id", groupId)
                        .eq("user_id", userId)
        ) > 0;

        if (!exists) {
            return Result.fail("用户未加入该群组");
        }

        boolean removed = chatGroupMemberService.remove(
                new QueryWrapper<ChatGroupMember>()
                        .eq("group_id", groupId)
                        .eq("user_id", userId)
        );

        if (removed) {
            // 用户成功退出后，更新群组成员数
            QueryWrapper<ChatGroupMember> chatGroupMemberQueryWrapper = new QueryWrapper<>();
            chatGroupMemberQueryWrapper.eq("group_id", groupId);
            Long memberCount = chatGroupMemberService.count(chatGroupMemberQueryWrapper);
            int memberCountInt = memberCount.intValue();

            chatGroupService.update().set("member_count", memberCountInt).eq("group_id", groupId);

            return Result.success("成功退出群组");
        }

        return Result.fail("退出失败");
    }

    /**
     * 搜索群
     * GET /groups/search?keyword=xxx
     */
    @GetMapping("/search")
    public Result<Object> search(@RequestParam String keyword) {
        List<ChatGroup> groups = chatGroupService.list(
                new QueryWrapper<ChatGroup>()
                        .like("group_name", keyword)
        );
        Map<String, Object> data = new HashMap<>();
        data.put("list", groups);
        return Result.success(data);
    }

    /**
     * 创建群组
     * POST /groups
     */
    @PostMapping
    public Result<Object> create(@RequestBody CreateGroupRequest req){
        if (req==null || req.getName()==null || req.getName().trim().isEmpty()){
            return Result.fail("群组名称不能为空");
        }
        // 创建群
        ChatGroup g = new ChatGroup();
        g.setGroupName(req.getName().trim());
        g.setGroupAnnouncement(req.getDescription());
        g.setCreatorId(req.getCreatorId());
        g.setMemberCount(0);
        g.setCreateTime(new Date());
        g.setUpdateTime(new Date());
        chatGroupService.save(g);

        // 插入成员（包含创建者）
        Set<Long> memberIds = new HashSet<>();
        if (req.getMemberIds()!=null){
            memberIds.addAll(req.getMemberIds());
        }
        if (req.getCreatorId()!=null){
            memberIds.add(req.getCreatorId());
        }
        for (Long uid : memberIds){
            ChatGroupMember m = new ChatGroupMember();
            m.setGroupId(g.getGroupId());
            m.setUserId(uid);
            m.setJoinTime(new Date());
            m.setIsAdmin(Objects.equals(uid, req.getCreatorId()) ? 1 : 0);
            chatGroupMemberService.save(m);
        }
        // 更新成员数
        g.setMemberCount(memberIds.size());
        chatGroupService.updateById(g);

        Map<String,Object> data = new HashMap<>();
        data.put("id", g.getGroupId());
        return Result.success(data);
    }

}

